package cn.wjssl.domain.strategy.service.armory;

import cn.wjssl.domain.strategy.model.entity.StrategyAwardEntity;
import cn.wjssl.domain.strategy.model.entity.StrategyEntity;
import cn.wjssl.domain.strategy.model.entity.StrategyRuleEntity;
import cn.wjssl.domain.strategy.repository.IStrategyRepository;
import cn.wjssl.types.common.Constants;
import cn.wjssl.types.enums.ResponseCode;
import cn.wjssl.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * 奖池装配
 */
@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository repository;

    /**
     * 根据活动Id, 查询策略Id
     * @param activityId
     * @return
     */
    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = repository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    /**
     * 根据策略id, 查询到对应的奖品和奖品的概率, 同时查询策略规则, 根绝规则配置奖池, 并存放到redis中
     * @param strategyId 策略ID
     * @return
     */
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        // 1. 通过 策略Id 获取对应的 List<StrategyAwardEntity>, 并缓存
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);

        // 2. 缓存奖品库存
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCount = strategyAwardEntity.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        // 3. 先初始化全量奖池
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);

        /**
         * 4. 查询 Strategy 表 ,查询到对应的 StrategyEntity 对象, 并获取抽奖前置策略 rule_model
         * 如果在 rule_model 中，没有 rule_weight 权重信息, 那就直接返回true
         * 如果有 rule_weight 权重信息, 再根据 (strategyId, rule_model), 查询 Strategy_rule 表, 并获取具体的 rule_value
         * 根据 rule_value 装配权重奖池
         */
        // 获取抽奖前置规则 rule_model, 查询对应的权重信息
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleModel = strategyEntity.getRuleWeight2ruleModel();
        // 如果没有策略规则, 直接返回
        if (ruleModel == null) return true;
        // 如果有策略规则, 但是strategy_rule表中没有配置, 就报异常
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleModel);
        if (null == strategyRuleEntity) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        // 获得权重map, {"20:102,103,104",[102, 103, 104], ...}
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        // 轮询, 通过key获取奖品list, 克隆一个全量奖池的list, 从所有奖品类型中, 把奖品列表中没有的从全量奖品list中移除
        ruleWeightValueMap.keySet().forEach(key -> {
            List<Integer> awardIdList = ruleWeightValueMap.get(key);
            List<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(e -> !awardIdList.contains(e.getAwardId()));
            // 根据每组权重奖品类型, 装配权重奖池
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        });

        return true;
    }

    /**
     * 缓存奖品库存
     * @param strategyId
     * @param awardId
     * @param awardCount
     */
    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }

    /**
     * 把原本的奖品装配程序提取出来, 装配奖池
     * @param key
     * @param strategyAwardEntities
     * @return
     */
    public boolean assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        // 获取概率的最小值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)     // 把集合换成 AwardRate
                .min(BigDecimal::compareTo)     // 比较 获取最小的概率
                .orElse(BigDecimal.ZERO);       // 防止出现 0
        // 概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);  // 从0开始累加

        // 用概率总和 除以 概率最小值 获取概率范围, 相当于总共有多少个奖品, 相当于奖品总数
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);
        // 初始化一个奖品集合 用来存放 AwardId
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        // 循环获取到的 策略奖品实体类, 并填充奖品集合
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            // 通过 奖品总数 乘以 概率,可以直到在总数内, 有多少个对应的奖品
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                // 填充奖品集合
                strategyAwardSearchRateTables.add(awardId);
            }
        }
        // 乱序,要不然会按顺序填充
        Collections.shuffle(strategyAwardSearchRateTables);

        // 创建一个 map 用来存放乱序后奖品总和的索引和对应的AwardID
        Map<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        // 8. 存放到 Redis
        repository.storeStrategyAwardSearchRateTable(key, shuffleStrategyAwardSearchRateTable.size(), shuffleStrategyAwardSearchRateTable);

        return true;
    }

    /**
     * 无权重的奖池 抽奖
     * @param strategyId
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId) {
        // 因为如果是分布式部署的话, 做策略初始化的不一定是本机服务,所以要从redis中获取 奖品池
        int rateRange = repository.getRateRange(String.valueOf(strategyId));
        // 根据奖品池,随机一个id,从map中获取对应的awardID,就完成了随机抽奖
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    /**
     * 有权重的奖池 抽奖
     * @param strategyId
     * @param ruleWeightRuleValue
     * @return
     */
    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightRuleValue) {
        // 从有权重的对应的redis中获取奖池
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightRuleValue);
        int rateRange = repository.getRateRange(key);
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    /**
     * 库存扣减方法
     * @param strategyId
     * @param awardId
     * @return 是否还有库存
     */
    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey, endDateTime);
    }

}
